//动漫页面的控制层
package com.happy.Animation.controllers;

import com.happy.Animation.dao.AuthorRepository;
import com.happy.Animation.dao.ClassificationRepository;
import com.happy.Animation.dao.CountryRepository;
import com.happy.Animation.dao.ProjectRepository;
import com.happy.Animation.entities.Author;
import com.happy.Animation.entities.Classification;
import com.happy.Animation.entities.Country;
import com.happy.Animation.entities.Project;
import com.happy.Animation.services.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("projects")
public class ProjectController {

    @Autowired
    ClassificationRepository classificationRepository;

    @Autowired
    CountryRepository countryRepository;

    @Autowired
    ProjectService projectService;

    @Autowired
    AuthorRepository authorRepository;

    @Autowired
    ProjectRepository projectRepository;

    @GetMapping
    public String displayProjects(Model model){
        List<Project> projects=projectService.getAll();
        model.addAttribute("projects",projects);
        return "projects/list-projects";
    }

    @GetMapping("/new")
    public String displayProjectForm(Model model){

        Project aProject = new Project();
        List<Author> authors = authorRepository.findAll();
        List<Country> countries = countryRepository.findAll();
        List<Classification> classifications = classificationRepository.findAll();
        model.addAttribute("project", aProject);
        model.addAttribute("allAuthors",authors);
        model.addAttribute("allCountries",countries);
        model.addAttribute("allClassifications",classifications);
        return "projects/new-project";
    }

    @PostMapping("/save")
    public String createProject(
            Model model,
            @RequestParam List<Long> authors,
            @RequestParam List<Long> countries,
            @RequestParam List<Long> classifications,
            Project project){
        //处理保存到数据库的行为
        projectService.save(project);
        Iterable<Author> chosenAuthors = authorRepository.findAllById(authors);
        for (Author author:chosenAuthors){
            author.setProject(project);
            authorRepository.save(author);
        }

        Iterable<Country> chosenCountries = countryRepository.findAllById(countries);
        for (Country country:chosenCountries){
            country.setProject(project);
            countryRepository.save(country);
        }
        //使用重新定位防止重复提交
        return "redirect:/projects";
    }
}
